package com.neusoft.neu24.nep.bootaop.demos.interceptor;


import com.neusoft.neu24.nep.bootaop.demos.entity.CommonResult;
import com.neusoft.neu24.nep.bootaop.demos.entity.HttpCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

@RestControllerAdvice
@Slf4j
@CrossOrigin("*")
public class GlobalExceptionHandler {

    @Autowired
    private HttpServletRequest httpServletRequest;


    private final String sysError="系统出错";


    /**
     * NoHandlerFoundException 异常捕获处理
     * 请求的接口不存在
     */
    @ExceptionHandler(NoHandlerFoundException.class)
    public CommonResult noHandlerFoundExceptionHandler(HttpServletRequest request, NoHandlerFoundException e) {
        log.error("BAD_REQUEST|{}|{}: {}|{}", null != request ? request.getRequestURI() : "", e.getClass().getSimpleName(), e.getMessage(), null != request ?
               e.getMessage() : "");
        return   new CommonResult(HttpCodeEnum.SYSTEM_ERROR.getCode() ,sysError, null );
    }

    //.....拦截异常方法
    /**
     * 缺少请求体异常处理器
     * @param e 缺少请求体异常 使用get方式请求 而实体使用@RequestBody修饰
     */
    @ResponseStatus(  HttpStatus.NOT_FOUND)
    public CommonResult  parameterBodyMissingExceptionHandler(HttpMessageNotReadableException e) {
        String requestURI = httpServletRequest.getRequestURI();
        log.error("请求地址'{}',请求体缺失'{}'", requestURI, e.getMessage());
//        return ResponseResult.errorResult(HttpCodeEnum.SYSTEM_ERROR.getCode(), sysError);
        return   new CommonResult(HttpCodeEnum.SYSTEM_ERROR.getCode() ,sysError, null );
    }


    /**
     * 处理其他异常
     *
     * @param e otherException
     * @return
     */
    @ExceptionHandler(Exception.class)
    public CommonResult exception(Exception e) {
        log.error("未知异常 exception = {}", e.getMessage(), e);
        return  new CommonResult(HttpCodeEnum.SYSTEM_ERROR.getCode() ,e.getMessage(), null );
    }




}
